﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Components.Forms;

namespace Bootstrap5.Components.Forms;

public static class FormControlExtensions
{
    public static string GetFeedbackCssClass(this EditContext editContext,in FieldIdentifier fieldIdentifier)
    {
        var isModified = editContext.IsModified(fieldIdentifier);
        var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any();
		if (isModified)
        {
            return isValid ? "modified is-valid" : "modified is-invalid";
        }
		if (!isValid)
		{
            return "is-invalid";
		}
        return string.Empty;
    }

    /// <summary>
    /// Returns the value of <see cref="DisplayAttribute.Name"/> from field expression.
    /// </summary>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="field"></param>
    /// <returns>The value of <see cref="DisplayAttribute.Name"/> or null.</returns>
    public static string GetDisplayName<TValue>(this Expression<Func<TValue>> field)
    {
        return ((MemberExpression)field?.Body)?.Member?.GetCustomAttribute<DisplayAttribute>()?.Name;
    }

    public static bool TryGetDisplayName<TValue>(this Expression<Func<TValue>> field,out string value)
	{
        value= field.GetDisplayName<TValue>();
        return !string.IsNullOrEmpty(value);
    }
}
